var video = {
  height: 720,
  width: 1280,
  top: 0,
  left: 0,
  abs_top: -1,
  abs_left: -1,
  seriesId: '',
  type: 'normal',
  controls: false,
  index: 0,
  el: '',
  _duration: 0,
  _currentTime: 0,
  _playTimer: false,
  _lock: false,
  _barW: 900,
  _playermode: 'normal',
  mp: null,
  _starttime: -1,
  _full: false,
  _oldVolume: 100,
  _volumeTimer: null,
  isInit: false,
  /**
   * 1、根据剧头详情获取视频播放列表
   * 2、剧头id鉴权
   * 3、初始化播放器
   */
  init: function (option) {
    for (var attr in option) {
      this[attr] = option[attr];
    }
    this._starttime = new Date().getTime()
    this.setSeriesId(this.seriesId)
    this.isInit = true
    return this
  },
  setSeriesId: function (seriesId) {
    this.seriesId = seriesId
    if (!this.seriesId) { return }
    this.index = 0
    this.getPlaylist()
    if (this.type == 'live') {
      this.playLive()
    } else {
      this.implementPlay(this.index)
    }
  },
  getPlaylist: function () {
    var data = getVodDetailInfo(this.seriesId)
    
    page.data.program = data
    page.data.playList = data.sitcomList
  },
  // 浏览器使用 video标签
  _renderError: function () {

    var _this = this
    if (!this.el) return
    $(this.el).append('<video width="' + this.width + '" height="' + this.height + '"  src=""></video>') //./images/templates/cs1.mp4
    this._oVideo = document.querySelector('video')
    this._oVideo.addEventListener('ended', function () {
      _this.goUtility()
    })
  },
  // 初始化视频
  _initMediaPlay: function () {
    var videoDisplayMode = 1;
    if (this.height == 720 && this.width == 1280) {
      this.left = 0;
      this.top = 0;
      this._full = true;
    } else {
      this._full = false;
      videoDisplayMode = 0;
    }
    this.destroy();
    try {
      this.mp = new MediaPlayer();
    var data = page.data.playList[this.index]
    var vodPlayUrl = utils.getPlayUrl(data.code)
    var instanceId = this.mp.getNativePlayerInstanceID();
    var playListFlag = 0;
    var muteFlag = 0;
    var useNativeUIFlag = 1;
    var subtitleFlag = 0;
    var videoAlpha = 0;
    var cycleFlag = 0;
    var randomFlag = 0;
    var autoDelFlag = 0;
    var mediaStr = '[{mediaUrl:"' + vodPlayUrl + '",';
    mediaStr += 'mediaCode: "jsoncode1",';
    mediaStr += 'mediaType:2,';
    mediaStr += 'audioType:1,';
    mediaStr += 'videoType:1,';
    mediaStr += 'streamType:1,';
    mediaStr += 'drmType:1,';
    mediaStr += 'fingerPrint:0,';
    mediaStr += 'copyProtection:1,';
    mediaStr += 'allowTrickmode:1,';
    mediaStr += 'startTime:0,';
    mediaStr += 'endTime:20000,';
    mediaStr += 'entryID:"jsonentry1"}]';
    this.mp.refreshVideoDisplay();
    
    this.mp.initMediaPlayer(instanceId,
      playListFlag,
      videoDisplayMode,
      this.height,
      this.width,
      this.left,
      this.top,
      muteFlag,
      useNativeUIFlag,
      subtitleFlag,
      videoAlpha,
      cycleFlag,
      randomFlag,
      autoDelFlag);
     
    this.mp.setSingleMedia(mediaStr); //设置媒体播放器播放媒体内容
    this.mp.setAllowTrickmodeFlag(0); //设置是否允许trick操作。 0:允许 1：不允许
    this.mp.setNativeUIFlag(0); //播放器是否显示缺省的Native UI，  0:允许 1：不允许
    this.mp.setAudioTrackUIFlag(1); //设置音轨的本地UI显示标志 0:不允许 1：允许
    this.mp.setMuteUIFlag(1); //设置静音的本地UI显示标志 0:不允许 1：允许
    this.mp.setAudioVolumeUIFlag(1); //设置音量调节本地UI的显示标志 0:不允许 1：允许
    this.mp.setCycleFlag(1); //这句神奇的代码用于解决电视剧连续播放的问题
    if(this.abs_left > 0){
      this.mp.setVideoDisplayArea(this.abs_left,this.abs_top,this.width,this.height)
    }
    
    this.mp.refreshVideoDisplay();
    } catch (error) {
      this._renderError(error)
    }
    
  },
  // 播放
  _play: function () {
     try {
       panel.hide()
     } catch (error) {

     }
    if (this.mp) {
      this.mp.playByTime(1, 0, 1)
      this._oldVolume = this.mp.getVolume()
    } else {
      this._oVideo.play()
      this._oldVolume = this._oVideo.volume * 100
    }
    $('#play_title').html(page.data.playList[this.index].name)
    this._currentTime = 0
    this._duration = 0
    this.setBar(this._currentTime)
    this.startBar();
    if (this.controls) {
      this.showControls()
      try {
        panel.init()
      } catch (error) {
        console.log('panel init error')
      }
    }
  },
  // 设置进度条start
  startBar: function () {
    var self = this;
    clearInterval(this.timer);
    this.timer = setInterval(function () {
      var time = self.mp ? self.mp.getCurrentPlayTime() : self._oVideo.currentTime
      self.setBar(time)
    }, 1000);
  },

  stopBar: function () {
    clearInterval(this.timer);
    this.timer = null;
  },
  setBar: function (val) {
    this._duration = this.mp ? this.mp.getMediaDuration() : this._oVideo.duration
    this._currentTime = val >= this._duration ? this._duration : val <= 0 ? 0 : val
    $("#duration").html(utils.formatTime(this._duration))
    $("#currenttime").html(utils.formatTime(this.mp ?this.mp.getCurrentPlayTime():this._oVideo.currentTime))
    //$("#currenttime").html(utils.formatTime(this._currentTime))
    var width = Math.min(this._barW, (this._currentTime / this._duration) * this._barW)
    $("#play-progress-bar").css("width", width)
  },
  // 设置进度条end

  // control
  showControls: function () {
    var self = this
    var time = 5
    this.hideControls()
    $("#bg-shadow").addClass("show")
    this.controlsTimer = setTimeout(function () {
      self.hideControls();
    }, 1000 * time)
  },
  hideControls: function () {
    clearTimeout(this.controlsTimer);
    this.controlsTimer = null;
    $('#bg-shadow').removeClass('show');
  },
  // control

  destroy: function () {
    this.stopBar()
    if (this.mp) {
      var nativePlayerInstanceID = this.mp.getNativePlayerInstanceID();
      this.mp.stop();
      this.mp.refreshVideoDisplay()
      
      this.mp.releaseMediaPlayer(nativePlayerInstanceID)
      this.mp = null;
    }
    else {
      $('video').remove();
      this._oVideo = null
    }
    this.log()
  },
  // 视频播放完后回调
  goUtility: function () {
    if (this.type === 'live') {
      this.liveOver()
    } else if (this.type === 'normal') {
      this.playOver()
    }
  },
  playLive: function () {
    this._initMediaPlay()
    this._play()
    if (!this.isOrder() && this._full) {
      try {
        timer.init()
      } catch (error) {

      }
    }
  },
  playOver: function () {
    this.index++
    this.implementPlay(this.index)
  },
  liveNext: function () {
    try {
      series.next()
      this.setSeriesId(page.data.series[series.index].ID)
    } catch (error) {
      console.log('series 未实例化')
    }
    this.index = 0
  },
  /**
   * 1. 索引超出说明当前剧头已播放完
   * 2. 跳到下一个剧头
   * 3. 当前子集为免费才播放
   */
  liveOver: function () {
    this.index++
    if (this.index > page.data.playList.length - 1) {
      this.liveNext()
    } else {
      if (!this.isFree()) this.liveNext()
    }
    this.implementPlay(this.index)
  },

  implementPlay: function (index) {
    index = index || this.index
    this.index = index % page.data.playList.length
    if (this.isFree()) {
      this._initMediaPlay()
      this._play()
    } else {
      this.destroy()
      utils.order()
    }
  },

  isOrder: function () {
    return page.isSub == 0
  },

  // 鉴权结果、剧头、节目标识。有一项通过即为免费
  isFree: function () {
    var program = page.data.program
    var currentSitcom = page.data.playList[this.index]
    return page.isSub == 0 || program.charge == 0 || currentSitcom.charge == 0
  },

  forwardOrRewind: function (len) {

    if (this.mp) {
      this.mp.pause()
      this._currentTime = parseInt(this.mp.getCurrentPlayTime()) + len
    } else {
      this._oVideo.pause()
      this._currentTime = parseInt(this._oVideo.currentTime) + len
    }

    if (this._currentTime >= this._duration) {
      this._currentTime = this._duration
      this.mp && this.mp.gotoEnd()
    } else if (this._currentTime <= 0) {
      this._currentTime = 0
    }

    if (this.mp) {
      this.mp.playByTime(1, this._currentTime, 1)
    } else {
      this._oVideo.currentTime = this._currentTime
      this._oVideo.play()
    }

    this.setBar(this._currentTime)
  },
  pause: function () {
    this._playermode = 'pause'
    this.mp ? this.mp.pause() : this._oVideo.pause()
    if (this.controls) {
      $("#pause").css("display", "block")
      this.showControls()
      this.stopBar()
    }
  },
  resume: function () {
    this.__playermode = 'normal'
    this.mp ? this.mp.resume() : this._oVideo.play()
    if (this.controls) {
      $("#pause").css("display", "none")
      this.showControls()
      this.startBar()
    }
  },
  // 暂停、播放
  playOrPause: function () {
    if (this._playermode === 'normal') {
      this.pause()
    } else {
      this.resume()
    }
  },
  log: function () {
    var endtime = new Date().getTime()
    var program = page.data.program ? page.data.program : {}
    var href = location.pathname
    var path = href.substring(href.lastIndexOf('/') + 1, href.indexOf('.'))
    log.commit({
      name: program.name,
      type1: 'vod',
      type2: path,
      code: program.code,
      id: program.ID,
      starttime: this._starttime,
      endtime: endtime
    })
    this._starttime = endtime
  },

  changeVolume: function (volume) {
    clearTimeout(this._volumeTimer)

    volume = volume <= 0 ? 0 : volume >= 100 ? 100 : volume

    $("#volume").css("display", "block")
    var src = volume == 0 ? "./images/controls/mute.png" : "./images/controls/volum.png"
    $("#volume img").attr("src", src)

    if (this.mp) {
      this.mp.setVolume(volume)
    } else {
      this._oVideo.volume = volume / 100
    }

    $("#volume-bar").css("height", volume + "%")
    this._volumeTimer = setTimeout(function () {
      $("#volume").css("display", "none")
    }, 3000)

  },

  volumeDown: function () {
    var volume
    if (this.mp) {
      volume = this.mp.getVolume()
    } else {
      volume = this._oVideo.volume * 100
    }
    volume -= 10;
    this.changeVolume(volume);
  },
  volumeUp: function () {
    var volume
    if (this.mp) {
      volume = this.mp.getVolume()
    } else {
      volume = this._oVideo.volume * 100
    }
    volume += 10;
    this.changeVolume(volume);
  },

  toggleMute: function () {
    var volume
    if (this.mp) {
      volume = this.mp.getVolume()
    } else {
      volume = this._oVideo.volume * 100
    }

    if (volume > 0) {
      this._oldVolume = volume
      volume = 0
    } else {
      volume = this._oldVolume
    }

    this.changeVolume(volume)
  }
}